package com.jf.ai.service;


import com.alibaba.dashscope.audio.tts.SpeechSynthesisResult;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.jf.ai.util.FileUtil;
import io.reactivex.Flowable;

import java.nio.ByteBuffer;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2025-06-17
 * Time:14:18
 */
public class AudioService {
    private static final String apiKey = "sk-e1dc69e1a9f24e50bd3155c0f18f2c09";
    private static final String model = "cosyvoice-v2";
    private static final String voice = "loongbella_v2";

    private SpeechSynthesisParam param;

    public AudioService() {
        param = SpeechSynthesisParam.builder()
                .apiKey(apiKey)
                .model(model)
                .voice(voice)
                .build();
    }

    public void generateAudioSync(String text) {
        SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(param, null);
        try {
            Flowable<SpeechSynthesisResult> resultFlowable = speechSynthesizer.callAsFlowable(text);
            resultFlowable.blockingForEach(result -> {
                ByteBuffer audioFrame = result.getAudioFrame();
                if (audioFrame != null) {
                    FileUtil.writeToFile("audio.mp3", audioFrame);
                }
            });
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        }
    }

    public void generateAudioAsync(String text) {
        SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(param, new ResultCallback<>() {
            @Override
            public void onEvent(SpeechSynthesisResult speechSynthesisResult) {
                ByteBuffer audioFrame = speechSynthesisResult.getAudioFrame();
                if (audioFrame != null) {
                    FileUtil.writeToFile("audio2.mp3", audioFrame);
                }
            }

            @Override
            public void onComplete() {
                System.out.println("complete");
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
        speechSynthesizer.streamingCall(text);
        speechSynthesizer.streamingComplete();
    }
}
